import base64
import hashlib
import hmac
import json
import os
import time
from hashlib import sha256
import requests

# 接口调用域名，正式环境域名：https://openapi.esign.cn 沙箱环境域名：https://smlopenapi.esign.cn


host = "https://openapi.esign.cn"
# 应用ID
appId = "5111710704"  # 7438906628
# 应用密钥
appKey = "b2ed72482e32e70f34912f1a47c676cf"
# 请求的与实体对应的MIME信息
contentType = "application/json; charset=UTF-8"


#计算MD5值
def md5_base64_byte(string):
    m = hashlib.md5()
    m.update(string.encode('utf-8'))
    # 二进制数据字符串值
    md5_str = m.digest()
    b64_str = base64.b64encode(md5_str)
    return b64_str


# 构建post请求
class HttpHelper(object):
    # 构建请求头
    @staticmethod
    def doPOST(url, reqBodyData):
        HTTPMethod = "POST"
        accept = "*/*"
        # 请求的与实体对应的MIME信息
        contentType = "application/json; charset=UTF-8"
        # 对请求的url进行签名
        accountsApiUrl = host+url
        date = ""
        headers = ""

        # 毫米时间戳获取
        t = time.time()
        # 毫秒级时间戳
        _timestamp = str(round(t * 1000))
        # 计算请求参数MD5值 ,其中contentMD5是指 Body 的 MD5 值，只有当 Body 非 Form 表单时才计算 MD5
        contentMD5 = md5_base64_byte(reqBodyData)
        contentMD5 = str(contentMD5, 'utf-8').format(contentMD5)
        # print('contentMD5=',contentMD5)  #打印MD5值
        # 构建参与请求签名计算的明文
        plain_text = '{}\n{}\n{}\n{}\n{}'.format(HTTPMethod, accept, contentMD5, contentType, date)
        if (headers != ""):
            plain_text1 = '{}\n{}\n{}'.format(plain_text, headers, url)
        else:
            plain_text1 = '{}{}\n{}'.format(plain_text, headers, url)
        # 使用HmacSHA256算法哈希(哈希秘钥为secret)，再对hash值使用Base64加密得到最终的签名值sign
        digest_str = hmac.new(appKey.encode('utf-8'), plain_text1.encode('utf-8'), digestmod=sha256).digest()
        reqSignature = base64.b64encode(digest_str).decode("utf-8")
        # 打印签名值
        # print('reqSignature=', reqSignature)
        # 构建请求头
        headers = {
            'X-Tsign-Open-App-Id': appId,
            'X-Tsign-Open-Auth-Mode': "Signature",
            'X-Tsign-Open-Ca-Timestamp': _timestamp,
            'Content-Type': contentType,
            'Accept': accept,
            'X-Tsign-Open-Ca-Signature': reqSignature,
            'Content-MD5': contentMD5
        }
        r = requests.post(accountsApiUrl, reqBodyData, headers=headers).text
        return r

    
    #  构建文件流上传请求
    @staticmethod
    def doPUT(uploadUrl1,file,contentType,contentMd5):
        headers = {
            'Content-Type': contentType,
            'Content-MD5': contentMd5
        }
        binfile = open(file, 'rb')
        r = requests.put(uploadUrl1, binfile, headers=headers).text
        return r

    @staticmethod
    def doGet(url, reqBodyData):
        HTTPMethod = "GET"
        accept = "*/*"
        # 请求的与实体对应的MIME信息
        contentType = "application/json; charset=UTF-8"
        # 对请求的url进行签名
        accountsApiUrl = host+url
        date = ""
        headers = ""
        # 毫米时间戳获取
        t = time.time()
        # 毫秒级时间戳
        _timestamp = str(round(t * 1000))
        # 计算请求参数MD5值 ,其中contentMD5是指 Body 的 MD5 值，只有当 Body 非 Form 表单时才计算 MD5
        contentMD5 = md5_base64_byte(reqBodyData)
        contentMD5 = str(contentMD5, 'utf-8').format(contentMD5)
        # print('contentMD5=',contentMD5)  #打印MD5值
        # 构建参与请求签名计算的明文
        plain_text = '{}\n{}\n{}\n{}\n{}'.format(HTTPMethod, accept, contentMD5, contentType, date)
        if (headers != ""):
            plain_text1 = '{}\n{}\n{}'.format(plain_text, headers, url)
        else:
            plain_text1 = '{}{}\n{}'.format(plain_text, headers, url)
        # 使用HmacSHA256算法哈希(哈希秘钥为secret)，再对hash值使用Base64加密得到最终的签名值sign
        digest_str = hmac.new(appKey.encode('utf-8'), plain_text1.encode('utf-8'), digestmod=sha256).digest()
        reqSignature = base64.b64encode(digest_str).decode("utf-8")
        headers = {
            'X-Tsign-Open-App-Id': appId,
            'X-Tsign-Open-Auth-Mode': "Signature",
            'X-Tsign-Open-Ca-Timestamp': _timestamp,
            'Content-Type': contentType,
            'Accept': accept,
            'X-Tsign-Open-Ca-Signature': reqSignature,
            'Content-MD5': contentMD5
        }
        result = requests.get(accountsApiUrl, json.loads(reqBodyData), headers=headers).text
        return result



